package com.javaweb.common;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class DispatcherTool {

    public static void responseWithInfo(HttpServletResponse resp, String url, String info) {
        try {
            //StringTool.URLEncodeInUTF(
            resp.sendRedirect(url + "?info=" + StringTool.URLEncodeInUTF(info));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void redirectTo(HttpServletResponse resp, String url) {
        try {
            resp.sendRedirect(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void redirectTo(HttpServletRequest req, HttpServletResponse resp, String logicUrl) {
        String fullUrl = req.getContextPath() + "/" + logicUrl ;
        redirectTo(resp, fullUrl);

    }

    /**
     *
     * @param req
     * @param resp
     * @param url
     * @param msg
     */
    public static void indirectForwardToClient(HttpServletRequest req, HttpServletResponse resp, String url, String msg) {
        try {
            String contextPath = req.getContextPath() ;
            System.out.println("[INFO] DispatcherTool, redirect to targetURL: " +(contextPath+ "/" + url)) ;
            req.getSession().setAttribute("msg", StringTool.URLEncodeInUTF(msg)) ;
            req.getSession().setAttribute("targetUrl", contextPath+ "/" + url) ;
            resp.sendRedirect(contextPath + "/01/servlet/message.jsp");

        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
